import os

import parsel
import sys

import pymysql

sys.path.append("..")

from src import facade
from src.facade import configdicts, urlQuery2List
from src.mylogger import MLogger
from src.mysqlfacade import MysqlUtiles

abspath = os.path.dirname(os.path.abspath(__file__))
configpath = os.path.join(abspath, "db.ini")


class ParaList(object):
    def __init__(self):
        self.logger = MLogger().streamlogger
        self.listdir = configdicts["path"]["path_step1"]
        self.mysqlutile = MysqlUtiles(configpath, "db", logger=self.logger)

    def para_all(self):
        for file in facade.get_dir_all_files(self.listdir):
            html = facade.single_read_file(file)
            self.para(html)

    def para(self, html):
        select = parsel.Selector(text=html)
        div_list = select.xpath('//*[@id="lblList"]/div')
        for div in div_list:
            strings = div.xpath('.//div[1]/div[3]/p').get()
            cover = div.xpath('.//div[1]/div[2]/a/img/@src').get()
            url = div.xpath('.//div[2]/a/@href').get()
            dicts = urlQuery2List(url)
            BaseID = dicts["BaseID"][0]
            strings = strings.replace("<p>", "").replace("</p>", "")
            msg_list = strings.split("<br>")
            journal_name = ''
            journal_name_alt = ''
            journal_name_used = ''
            publisher = ''
            impact_fh = ''
            impact_zh = ''
            cited_count = ''
            empower = ''
            for msg in msg_list:
                if msg.find("中文名称") > -1:
                    journal_name = msg.replace("中文名称：", "").strip()
                elif msg.find("英文名称") > -1:
                    journal_name_alt = msg.replace("英文名称：", "").strip()
                elif msg.find("曾用刊名") > -1:
                    journal_name_used = msg.replace("曾用刊名：", "").strip()
                elif msg.find("主办单位") > -1:
                    publisher = msg.replace("主办单位：", "").strip()
                elif msg.find("复合影响因子") > -1:
                    impact_fh = msg.replace("复合影响因子：", "").strip()
                elif msg.find("综合影响因子") > -1:
                    impact_zh = msg.replace("综合影响因子：", "").strip()
                elif msg.find("被引频次") > -1:
                    cited_count = msg.replace("被引频次：", "").strip()
                elif msg.find("独家授权") > -1:
                    empower = "独家授权"
                elif msg.find("优先出版") > -1:
                    empower = "优先出版"
                else:
                    if msg.strip():
                        self.logger.info(msg)
                        sys.exit(-1)
            journal_name_alt = pymysql.escape_string(journal_name_alt)
            journal_name_used = pymysql.escape_string(journal_name_used)

            sql = "insert ignore into journal(journal_name,journal_name_alt,journal_name_used,publisher,impact_fh,impact_zh,cited_count,empower,cover,url,baseid) values ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')"
            sql = sql % (
                journal_name, journal_name_alt, journal_name_used, publisher, impact_fh, impact_zh, cited_count,
                empower, cover, url, BaseID)
            self.mysqlutile.ExeSqlToDB(sql)


if __name__ == "__main__":
    para = ParaList()
    para.para_all()

""""
type_name 出版周期
pub_place 出版地
language 语种：  中文;
book_size 开本：  大16开
issn ISSN： 0517-6611
cnno CN：   34-1076/S
emailcode 邮发代号： 26-20

create_date 创刊时间

collect_abbr 该刊被以下数据库收录：

core_journal  核心期刊：
"""
